﻿using Ivony.Html;
using Ivony.Html.Parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Xwork.SEO.Providers
{
    class GoogleCNEngine : SearchEngineProvider
    {
        protected override string GetQueryUrl(string keyword)
        {
            return string.Format("http://www.google.com.hk/search?num=50&hl=zh-CN&newwindow=1&safe=strict&q={0}", HttpUtility.UrlEncode(keyword));
        }

        protected override SearchResult GetResult(string html, string site)
        {
            //Ivony.Html.Parser.DomDocument doc = new Ivony.Html.Parser.DomDocument(html);
            JumonyParser jp = new JumonyParser();
            IHtmlDocument doc = jp.Parse(html, new Uri("http://www.baidu.com/"));
            IEnumerable<IHtmlElement> list = doc.Find("li.g cite");
            int index = 1;
            foreach (var item in list)
            {
                string url = item.InnerHtml();
                if (!string.IsNullOrWhiteSpace(url))
                {
                    url = url.Trim();
                    if (url.StartsWith(site))
                    {
                        return new SearchResult { Index = index, Found = true };
                    }
                }
                index++;
            }
            return new SearchResult { Index = -1, Found = false };
        }
    }
}
